package com.allen.retrofit2_rxjava2.view.selectImage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.retrofit2_rxjava2.R;
import com.allen.retrofit2_rxjava2.base.TitleViewActivity;
import com.allen.retrofit2_rxjava2.utils.MainUtil;
import com.allen.retrofit2_rxjava2.utils.ToastUtils;
import com.allen.retrofit2_rxjava2.view.calendar.CalendarActivity;
import com.allen.retrofit2_rxjava2.view.selectImage.adapter.FeedbackImageAdapter;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.ChooseUploadParam;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.FeedbackParam;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.ImgParam;
import com.allen.retrofit2_rxjava2.view.selectImage.view.GridItemDecoration;
import com.allen.retrofit2_rxjava2.view.selectImage.view.UpLoadImgDialog;
import com.allen.retrofit2_rxjava2.view.selectimageview.utils.CameraUtil;
import com.ieyelf.service.util.Logger;
import com.java.luban.Luban;
import com.java.luban.OnCompressListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


//意见反馈页面
public class FeedbackActivity extends TitleViewActivity implements View.OnClickListener, FeedbackImageAdapter.OnItemClickListener, FeedbackImageAdapter.OndeleteItemClickListener {

    private String TAG = "FeedbackActivity";
    public static final int REQUEST_PHONE = 299;
    private static final int REQUEST_PHOTO = 100;
    private static final int PREVIEW_PHOTO = 112;
    private RecyclerView rv_feedback;
    private FeedbackImageAdapter adapter;
    private EditText et_content;
    private ArrayList<ChooseUploadParam> params;
    private Button btn_feedback;
    private UpLoadImgDialog upLoadImgDialog;//上传照片的dialog
    private ArrayList<ChooseUploadParam> selectingParams;
    private TextView t1;
    /**
     * Android 6.0以上版本，需求添加运行时权限申请；否则，可能程序崩溃
     */
    private static final int REQUEST_CODE_PERMISSION = 0x110;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        checkPermission();
        initTitleBar();
        initView();
        initData();
    }

    private void initTitleBar() {
        initTitleView();
        setCenterViewContent("选择图片");
        initLeftBackView(null);
    }


    private void initView() {
        t1 = (TextView) findViewById(R.id.t1);
        t1.setOnClickListener(this);
        rv_feedback = (RecyclerView) findViewById(R.id.rv_feedback);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        et_content = (EditText) findViewById(R.id.et_feedcontent);
        et_content.addTextChangedListener(mTextWatcher);
        rv_feedback.setLayoutManager(gridLayoutManager);
        rv_feedback.setItemAnimator(new DefaultItemAnimator());
        int itemDecoration = getResources().getDimensionPixelSize(R.dimen.itemDecoration);
        rv_feedback.addItemDecoration(new GridItemDecoration(itemDecoration));
        btn_feedback = (Button) findViewById(R.id.btn_feedback);
        btn_feedback.setOnClickListener(this);

        selectingParams = new ArrayList<>();

        et_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    et_content.getText().clear();
                }
            }
        });


    }

    private void initData() {
        params = new ArrayList<>();
        ChooseUploadParam param = new ChooseUploadParam();
        param.setType(FeedbackImageAdapter.TYPE_ADD);
        params.add(param);
        adapter = new FeedbackImageAdapter(this, params);
        adapter.setOnItemClickListener(this);
        adapter.setOndeleteItemClickListener(this);
        rv_feedback.setAdapter(adapter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_feedback:
                break;
            case R.id.t1:
                startActivity(new Intent(this, CalendarActivity.class));
                break;
            default:
                break;
        }
    }

    //从手机中选择图片和视频
    private void chooseFromPhone() {
        Intent intent = new Intent(this, SelectPhotoActivity.class);
        intent.putExtra("maxLeftCount", 3 - adapter.getImgCount());
        startActivityForResult(intent, REQUEST_PHONE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainUtil.log(data + ":" + (resultCode == RESULT_OK));
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PHONE:
                handlePhone(data);
                break;
            case REQUEST_PHOTO:
                handlePhoto();
                break;
            case PREVIEW_PHOTO:

//                params = data.getParcelableArrayListExtra("data");
//
//                if (selectingParams.size() == 3) {
//                    if (params.size() == 0 || params.size() < 3) {
//                        selectingParams.clear();
//                        selectingParams.addAll(params);
//                        ChooseUploadParam param = new ChooseUploadParam();
//                        param.setType(FeedbackImageAdapter.TYPE_ADD);
//                        params.add(param);
//                    }
//                }
//
//                adapter.updateListView(params);
//                adapter.notifyDataSetChanged();

                break;


        }
    }

    /**
     * 处理拍照之后返回的信息
     */
    private void handlePhoto() {
        String filename = CameraUtil.getRealFilePath();
        if (TextUtils.isEmpty(filename)) {
            showToast("拍摄照片为空");
            return;
        }
        List<String> fileList = new ArrayList<String>();
        fileList.add(filename);
        luBan(fileList);
    }

    /**
     * 相册选择的图片
     *
     * @param data
     */
    private void handlePhone(Intent data) {
        if (data == null) {
            Log.e(TAG, "从手机中获取数据失败");
            return;
        }
        ArrayList<ChooseUploadParam> params = data.getParcelableArrayListExtra("data");
        ArrayList<ChooseUploadParam> newp = new ArrayList<ChooseUploadParam>();
        try {
            if (params.size() == 0) {
                Log.e(TAG, "Intent返回数据为空:" + data);
                return;
            } else {
                List<String> fileList = new ArrayList<String>();
                for (ChooseUploadParam choos : params) {
                    fileList.add(choos.getPath());
                }
                luBan(fileList);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    @Override
    public void onItemClick(int position, int viewType, ChooseUploadParam param) {
        switch (viewType) {
            case FeedbackImageAdapter.TYPE_ADD://添加的图标
                showImageDialog();
                break;
            case FeedbackImageAdapter.TYPE_IMG://添加的图标
                Intent intent = new Intent(this, PreviewActivity.class);
                intent.putParcelableArrayListExtra("select", selectingParams);
                intent.putExtra("initPosition", position);
                startActivityForResult(intent, PREVIEW_PHOTO);
                break;
        }
    }

    //用户输入长度监听条件
    TextWatcher mTextWatcher = new TextWatcher() {
        private TextView view;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            view = (TextView) findViewById(R.id.textnumber);
            int num = s.length();
            if (num > 0) {
                btn_feedback.setEnabled(true);
            }
//            num = 120 - num;
            view.setText(num + "/200");

        }
    };


    private void showImageDialog() {
        if (upLoadImgDialog == null) {
            upLoadImgDialog = new UpLoadImgDialog(FeedbackActivity.this, new ImageListener());
        }
        upLoadImgDialog.show();
    }

    @Override
    public void ondeleteItemClick(int position) {
        selectingParams.remove(position);
    }

    /**
     * 上传图片监听器
     */
    class ImageListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_dialog_camera:
                    if (upLoadImgDialog != null) {
                        upLoadImgDialog.dismiss();
                    }
                    checkTakePhotoPermission();
                    break;
                case R.id.tv_dialog_gallery:
                    if (upLoadImgDialog != null) {
                        upLoadImgDialog.dismiss();
                    }
                    checkWriteStoragePermission();
                    break;
            }
        }
    }

    private void checkTakePhotoPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M // Permission was added in API Level 16
                && (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.CAMERA
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PHOTO);
        } else {
            takePhoto();
        }
    }

    private void checkWriteStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PHONE);
        } else {
            chooseFromPhone();
        }
    }

    //拍照
    private void takePhoto() {

        if (ContextCompat.checkSelfPermission(FeedbackActivity.this,
                Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            startActivityForResult(CameraUtil.getCameraIntent(FeedbackActivity.this), REQUEST_PHOTO);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PHOTO:
                if (grantResults.length < 0) {
                    return;
                }
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.showToast(getResources().getString(R.string.camera_forbidden));
                    break;
                }
                if (grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    break;
                }
                Log.d(TAG, "请求拍照权限成功");
                takePhoto();
                break;

            case REQUEST_PHONE:
                if (grantResults.length < 0) {
                    return;
                }
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    break;
                } else {
                    chooseFromPhone();
                }
                break;
            case REQUEST_CODE_PERMISSION:
//                switch (grantResults[0]) {
//                    case PackageManager.PERMISSION_DENIED:
//                        boolean isSecondRequest = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA);
//                        if (isSecondRequest)
//                            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION);
//                        else
//                            Toast.makeText(this, "拍照权限被禁用，请在权限管理修改", Toast.LENGTH_SHORT).show();
//                        break;
//                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }

    }

    /**
     * 发送到http服务器
     */
    private void sendhttp() {
        List<ImgParam> imgParams = new ArrayList<>();
        for (ChooseUploadParam param : adapter.getParams()) {
            switch (param.getType()) {
                case FeedbackImageAdapter.TYPE_IMG:
                    ImgParam imgParam = new ImgParam();
                    imgParam.setPath(param.getPath());
                    imgParams.add(imgParam);
                    break;
            }
        }
    }

    /**
     * 异步
     * 鲁班图片压缩
     */
    private void luBan(List<String> paths) {
        Luban.with(this)
                .load(paths)
                .ignoreBy(1024)
                .setTargetDir(CameraUtil.getFilePath())
                .setFocusAlpha(false)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        Logger.verbose(file.getAbsolutePath());
                        try {
                            String filepath = file.getAbsolutePath();
                            ChooseUploadParam param = new ChooseUploadParam();

                            //压缩下拍照后的图片 保存新路径 上传
                            param.setType(FeedbackImageAdapter.TYPE_IMG);
                            param.setPath(filepath);
                            MainUtil.log("filepath : " + filepath + "filesizw : " + file.length() / 1024);
                            adapter.addItem(param);
                            selectingParams.add(param);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }


    private void checkPermission() {
        List<String> permissionLists = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissionLists.add(Manifest.permission.CAMERA);
        }
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionLists.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!permissionLists.isEmpty()) {// 说明肯定有拒绝的权限
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != upLoadImgDialog) {
            upLoadImgDialog = null;
        }
    }

}